package Receivers

import (
	"gitee.com/ling-bin/network/netInterface"
	"strconv"
)

//SpliceStartAndDataLengthHexReceiver 开始加数据长度分包算法
type SpliceStartAndDataLengthHexReceiver struct {
	startSymbol     []byte
	startSymbolLen  int
	appendCount     int
	dataLengthCount int
	dataLengthIndex int
	hLen            int
}

//NewSpliceStartAndDataLengthHexReceiver 开始加数据长度分包算法
func NewSpliceStartAndDataLengthHexReceiver(startSymbol []byte,appendCount int,dataLengthIndex int,dataLengthCount int) *SpliceStartAndDataLengthHexReceiver {
	return &SpliceStartAndDataLengthHexReceiver{
		startSymbol:     startSymbol,
		startSymbolLen:  len(startSymbol),
		appendCount:     appendCount,
		dataLengthCount: dataLengthCount,
		dataLengthIndex: dataLengthIndex,
		hLen:            dataLengthIndex + dataLengthCount + len(startSymbol),
	}
}

//GetHeadLen 包头必须要的长度
func (s *SpliceStartAndDataLengthHexReceiver) GetHeadLen() int {
	return s.hLen
}

//CanHandle 是否能处理
func (s *SpliceStartAndDataLengthHexReceiver) CanHandle(conn netInterface.IConnection, buffer []byte) bool {
	isOk := true
	for i := 0; i < s.startSymbolLen; i++ {
		if s.startSymbol[i] != buffer[i] {
			isOk = false
		}
	}
	return isOk
}

//Reset 重置分包状态为初始状态
func (s *SpliceStartAndDataLengthHexReceiver) Reset()  {

}

//Receiver 分包处理
func (s *SpliceStartAndDataLengthHexReceiver) Receiver(conn netInterface.IConnection, buffer []byte) ([]byte, int) {
	var (
		bfLen         = len(buffer)
		startIndex    = -1
		startOkLen    = 0
		isStart       = false
		currentLength = 0
		packetLen     = 0
	)
	for i := 0; i < bfLen; i++ {
		if !isStart {
			if buffer[i] == s.startSymbol[startOkLen] {
				startOkLen++
				if startOkLen == s.startSymbolLen {
					isStart = true
					startIndex = i
					currentLength = s.startSymbolLen
				}
			} else {
				isStart = false
			}
			continue
		}
		currentLength++
		if packetLen == 0 {
			lenStr := ""
			for j := 0; j < s.dataLengthCount; j++ {
				lenStr = lenStr + string(buffer[startIndex+s.dataLengthCount+j])
			}
			lenT, _ := strconv.ParseInt(lenStr, 16, 8)
			packetLen = int(lenT) + s.appendCount
			if packetLen+startIndex <= bfLen {
				hData := buffer[startIndex : startIndex+packetLen+1]
				startIndex = startIndex + packetLen + 1
				return hData, startIndex + packetLen + 1
			}
		}
		if packetLen != 0 {
			if currentLength >= packetLen {
				hData := buffer[startIndex : startIndex+packetLen+1]
				startIndex = startIndex + currentLength + 1
				return hData, startIndex + currentLength + 1
			}
		}
	}
	return nil, startIndex
}

